package cn.lngaosu.lwyd.module.integration.service.toutiaoaccount;

import cn.hutool.core.collection.CollUtil;
import cn.lngaosu.lwyd.framework.common.util.http.HttpUtils;
import cn.lngaosu.lwyd.module.infra.service.config.ConfigService;
import cn.lngaosu.lwyd.module.integration.dal.mysql.weibostatusesusertimeline.WeiboStatusesUsertimelineMapper;
import cn.lngaosu.lwyd.module.integration.service.weibocommentsshow.WeiboCommentsShowServiceImpl;
import cn.lngaosu.lwyd.module.system.dal.dataobject.webinterfacelog.WebinterfaceLogDO;
import cn.lngaosu.lwyd.module.system.dal.mysql.webinterfacelog.WebinterfaceLogMapper;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;
import cn.lngaosu.lwyd.module.integration.controller.admin.toutiaoaccount.vo.*;
import cn.lngaosu.lwyd.module.integration.dal.dataobject.toutiaoaccount.ToutiaoAccountDO;
import cn.lngaosu.lwyd.framework.common.pojo.PageResult;
import cn.lngaosu.lwyd.framework.common.pojo.PageParam;
import cn.lngaosu.lwyd.framework.common.util.object.BeanUtils;

import cn.lngaosu.lwyd.module.integration.dal.mysql.toutiaoaccount.ToutiaoAccountMapper;

import static cn.lngaosu.lwyd.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.convertList;
import static cn.lngaosu.lwyd.framework.common.util.collection.CollectionUtils.diffList;
import static cn.lngaosu.lwyd.module.integration.enums.ErrorCodeConstants.*;

/**
 * 今日头条账号基本信息 Service 实现类
 *
 * @author 张恒
 */
@Service
@Validated
public class ToutiaoAccountServiceImpl implements ToutiaoAccountService {
    private static final Logger logger = LoggerFactory.getLogger(ToutiaoAccountServiceImpl.class);

    @Resource
    private ToutiaoAccountMapper toutiaoAccountMapper;
    @Resource
    private ConfigService configService;
    @Resource
    private WebinterfaceLogMapper webinterfaceLogMapper;
    @Resource
    private WeiboStatusesUsertimelineMapper weiboStatusesUsertimelineMapper;

    @Override
    public Long createToutiaoAccount(ToutiaoAccountSaveReqVO createReqVO) {
        // 插入
        ToutiaoAccountDO toutiaoAccount = BeanUtils.toBean(createReqVO, ToutiaoAccountDO.class);
        toutiaoAccountMapper.insert(toutiaoAccount);
        // 返回
        return toutiaoAccount.getId();
    }

    @Override
    public void updateToutiaoAccount(ToutiaoAccountSaveReqVO updateReqVO) {
        // 校验存在
        validateToutiaoAccountExists(updateReqVO.getId());
        // 更新
        ToutiaoAccountDO updateObj = BeanUtils.toBean(updateReqVO, ToutiaoAccountDO.class);
        toutiaoAccountMapper.updateById(updateObj);
    }

    @Override
    public void deleteToutiaoAccount(Long id) {
        // 校验存在
        validateToutiaoAccountExists(id);
        // 删除
        toutiaoAccountMapper.deleteById(id);
    }

    @Override
        public void deleteToutiaoAccountListByIds(List<Long> ids) {
        // 校验存在
        validateToutiaoAccountExists(ids);
        // 删除
        toutiaoAccountMapper.deleteByIds(ids);
        }

    private void validateToutiaoAccountExists(List<Long> ids) {
        List<ToutiaoAccountDO> list = toutiaoAccountMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(TOUTIAO_ACCOUNT_NOT_EXISTS);
        }
    }

    private void validateToutiaoAccountExists(Long id) {
        if (toutiaoAccountMapper.selectById(id) == null) {
            throw exception(TOUTIAO_ACCOUNT_NOT_EXISTS);
        }
    }

    @Override
    public ToutiaoAccountDO getToutiaoAccount(Long id) {
        return toutiaoAccountMapper.selectById(id);
    }

    @Override
    public PageResult<ToutiaoAccountDO> getToutiaoAccountPage(ToutiaoAccountPageReqVO pageReqVO) {
        return toutiaoAccountMapper.selectPage(pageReqVO);
    }

    @Override
    public void syncToutiaoAccount() {
        // 接口配置
        String configValue = configService.getConfigValueByKey("toutiaoConfig");
        if (StringUtils.isEmpty(configValue)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        JSONObject configJo = JSONObject.parseObject(configValue);
        // 接口开关
        String onOff = configJo.getString("onOff");
        if (!"on".equals(onOff)) {
            throw exception(INTERFACE_CONFIG_NOT_EXISTS);
        }

        // 获取地址
        String baseInfoUrl = configJo.getString("baseInfoUrl");

        // 构造请求参数
        String token = configJo.getString("token");
        Map<String, Object> formData = new HashMap<>();
        formData.put("token", token);

        // 初始化日志数据（默认成功）
        WebinterfaceLogDO webinterfaceLogDO = new WebinterfaceLogDO();
        webinterfaceLogDO.setInterfaceSystemName("今日头条");
        webinterfaceLogDO.setInterfaceName("获取账号基本信息");
        webinterfaceLogDO.setInterfaceUrl(baseInfoUrl);
        webinterfaceLogDO.setInterfaceRequestMethod("POST");
        webinterfaceLogDO.setInterfaceParam(JSONObject.toJSONString(formData));
        webinterfaceLogDO.setInterfaceStatus("成功");
        webinterfaceLogMapper.insert(webinterfaceLogDO);

        try {
            String result = HttpUtils.postFormData(baseInfoUrl, new HashMap<>(), formData);
            // 解析接口结果
            JSONObject resultJo = JSONObject.parseObject(result);
            String message = resultJo.getString("message");
            if (!"success".equals(message)) {
                webinterfaceLogDO.setInterfaceStatus("失败");
                webinterfaceLogDO.setInterfaceErrorInfo(result);
                webinterfaceLogMapper.updateById(webinterfaceLogDO);
                return;
            }
            JSONObject dataJo = resultJo.getJSONObject("data");
            String digg_count = dataJo.getString("digg_count");
            String fans = dataJo.getString("fans");
            String following = dataJo.getString("following");

            ToutiaoAccountDO toutiaoAccountDO = new ToutiaoAccountDO();
            toutiaoAccountDO.setDiggCount(handleString2Num(digg_count));
            toutiaoAccountDO.setFans(handleString2Num(fans));
            toutiaoAccountDO.setFollowing(handleString2Num(following));
            toutiaoAccountDO.setDetailMessage(result);
            // 判断数据是否存在
            LambdaQueryWrapper<ToutiaoAccountDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.like(ToutiaoAccountDO::getCreateTime, LocalDate.now());
            List<ToutiaoAccountDO> toutiaoAccountDOS = toutiaoAccountMapper.selectList(queryWrapper);
            if (CollectionUtils.isNotEmpty(toutiaoAccountDOS)) {
                toutiaoAccountDO.setId(toutiaoAccountDOS.get(0).getId());
            }

            toutiaoAccountMapper.insertOrUpdate(toutiaoAccountDO);
        } catch (Exception e) {
            webinterfaceLogDO.setInterfaceStatus("失败");
            webinterfaceLogDO.setInterfaceErrorInfo(e.getMessage());
            webinterfaceLogMapper.updateById(webinterfaceLogDO);
            logger.error("微博【根据微博ID返回某条微博的评论列表】接口调用失败！", e);
        }
    }

    private Integer handleString2Num(String str) {
        int rtnNum = 0;
        if (ObjectUtils.isEmpty(str)) {
            return rtnNum;
        }

        if (str.contains("千")) {
            String replaceStr = str.replaceAll("千", "");
            rtnNum = new BigDecimal(replaceStr).multiply(BigDecimal.valueOf(1000L)).intValue();
        } else if (str.contains("万")) {
            String replaceStr = str.replaceAll("万", "");
            rtnNum = new BigDecimal(replaceStr).multiply(BigDecimal.valueOf(10000L)).intValue();
        } else {
            rtnNum = new BigDecimal(str).intValue();
        }

        return rtnNum;
    }

}